import { defineStore } from 'pinia'
import { ref } from 'vue'

// 定义 Store
export const useImgInfoStore = defineStore(
    'imgInfo',
    () => {

        const historyImgList = ref<any>([])
        const collectionImgList = ref<any>([])
        const pixivType = ref<number>(0) // 0:性感 1:R18  2:混合
        const searchRecord = ref<string[]>([])
        const addHistory = (item: any) => {
            // 判断是否已经存在
            if (historyImgList.value.some((i: any) => i.src === item.src)) return
            // 超出200条删除最早的一条
            if (historyImgList.value.length >= 200) {
                historyImgList.value.shift()
            }
            historyImgList.value.push(item)
        }
        const delHistory = (item: any) => {
            historyImgList.value = historyImgList.value.filter((i: any) => i.src !== item.src)
        }
        const clearHistory = () => {
            historyImgList.value = []
        }

        const addCollection = (item: any) => {
            // 判断是否已经收藏
            if (collectionImgList.value.some((i: any) => i.src === item.src)) return
            // 判断是否已经收藏 优化算法
            collectionImgList.value.push(item)
        }
        const delCollection = (item: any) => {
            collectionImgList.value = collectionImgList.value.filter((i: any) => i.src !== item.src)
        }
        const clearCollection = () => {
            collectionImgList.value = []
        }

        const setPixivType = (type: number) => {
            pixivType.value = type
        }
        const addRecord = (item: string) => {
            if (!item) return
            searchRecord.value = searchRecord.value.filter((i: string) => i !== item)
            if (searchRecord.value.length >= 50) {
                searchRecord.value.pop()
            }
            searchRecord.value.unshift(item)
        }
        const deleteRecord = (item: string) => {
            searchRecord.value = searchRecord.value.filter((i: string) => i !== item)
        }
        const clearRecord = () => {
            searchRecord.value = []
        }

        return {
            historyImgList,
            collectionImgList,
            pixivType,
            searchRecord,
            addHistory,
            delHistory,
            clearHistory,
            addCollection,
            delCollection,
            clearCollection,
            setPixivType,
            addRecord,
            deleteRecord,
            clearRecord
        }
    },

    {
        // 网页端
        // persist: true,
        // 小程序配置
        persist: {
            storage: {
                getItem(key) {
                    return uni.getStorageSync(key);
                },
                setItem(key, value) {
                    uni.setStorageSync(key, value);
                },
            }
        }
    },
)
